﻿using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Rud.Holmgren.Tabulex3000.Util;
using Rud.Holmgren.TabulexLib;
using Rud.Holmgren.Tabulex3000.CommunicationTasks;

namespace Rud.Holmgren.Tabulex3000
{
    public partial class MainPage : PhoneApplicationPage
    {
        private AppSettings appSettings;
        
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;

            appSettings = (App.Current.Resources["AppSettings"] as AppSettings);
            appSettings.PropertyChanged += HandleAppSettingsChanged;
        }

        private void HandleAppSettingsChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName.ToLower() == "username" || e.PropertyName.ToLower() == "password")
            {
                CommunicationManager.Instance.Clear();
                InitiateLogin();
            }
        }

        private void InitiateLogin()
        {
            if (!string.IsNullOrWhiteSpace(appSettings.Username) && !string.IsNullOrWhiteSpace(appSettings.Password))
            {
                var client = new TbxClient(appSettings.Username, appSettings.Password);
                var loginTask = new LoginTask(client);
                CommunicationManager.Instance.EnQueue(loginTask);
            }
        }


        // Load data for the ViewModel Items
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                appSettings.LoadSettings();
                App.ViewModel.LoadData();

                // var progressMgr = new SystemTrayProgressManager(this);
                var progressMgr = new UiControlsProgressManager(TheProgress, TheProgressText);
                CommunicationManager.Instance.Initialize(progressMgr);
                
                InitiateLogin();
            }
        }
    }
}